package com.yhm.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.yhm.dao.AllDAO;
import com.yhm.model.Dep;
import com.yhm.service.DepManager;

@Component("depManager")
public class DepManagerImpl implements DepManager{

	private AllDAO allDAO = new AllDAO();
	
	/**
	 * 获取全部部门名
	 */
	@SuppressWarnings("unchecked")
	public String get_dep(){
		String json = "";
		json = "{\"deps\":\""; 
		List<Dep> dep_list = (List<Dep>) allDAO.getDepDAO().findhql("from Dep d order by d.num ASC");
		for(Dep d:dep_list){
			json = json + d.getDepartment() + ",";
		}
		if(dep_list.size() != 0)
			json = json.substring(0, json.length()-1).concat("\"}");
		else
			json = json.concat("\"}");
		System.out.println(json);
		return json;
	}
	
	/**
	 * 部门列表
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String dep_list(){
		String json = "";
		List<?> dep_lists = allDAO.getDepDAO().findhql("select COUNT(*) from Dep d");
		int dep_lists_size = ((Long) dep_lists.get(0)).intValue();
		if(dep_lists_size == 0){
			json = "{\"total\":0,\"rows\":[]}";
			return json;
		}
		List<Dep> dep_list = (List<Dep>) allDAO.getDepDAO().findhql("from Dep d");
		json = "{\"total\":0," +
				"\"rows\":[";
		for(Dep dep : dep_list){
			json = json.concat("{\"num\":\"" + dep.getNum() + "\"," +
					"\"id\":\"" + dep.getId() + "\"," +
					"\"department\":\"" + dep.getDepartment() + "\"" +
					"},");
		}
		if(dep_list.size() != 0)
			json = json.substring(0, json.length()-1).concat("]}");
		else
			json = json.concat("]}");
		return json;
	}
	
	/**
	 * 添加部门
	 * @param dep
	 * @return
	 */
	public String dep_add(Dep dep){
		String json = "";
		try {
			allDAO.getDepDAO().save(dep);
			json = "{\"status\":0,\"mess\":\"添加部门成功！！\"}";
		} catch (Exception e) {
			json = "{\"status\":1,\"mess\":\"添加部门失败！！\"}";
		}
		return json;
	}
	
	/**
	 * 删除部门
	 * @param i
	 * @return
	 */
	public String dep_del(Dep dep){
		String json = "";
		try {
			allDAO.getDepDAO().delete(dep);
			json = "{\"status\":0,\"mess\":\"删除部门成功！！\"}";
		} catch (Exception e) {
			json = "{\"status\":1,\"mess\":\"删除部门失败！！\"}";
		}
		return json;
	}
	
	/**
	 * 修改部门
	 * @param i
	 * @param dep
	 * @return
	 */
	public String dep_update(Dep dep){
		String json = "";
		try {
			Dep d = (Dep) allDAO.getDepDAO().findById(dep.getId());
			d.setNum(dep.getNum());
			d.setDepartment(dep.getDepartment());
			allDAO.getDepDAO().attachDirty(d);
			json = "{\"status\":0,\"mess\":\"修改部门成功！！\"}";
		} catch (Exception e) {
			json = "{\"status\":1,\"mess\":\"修改部门失败！！\"}";
		}
		return json;
	}
	

	@Resource(name = "allDAO")
	public void setAllDAO(AllDAO allDAO) {
		this.allDAO = allDAO;
	}
}
